using System;
using DaaseVarmer.model;
using Microsoft.SPOT;
using DaaseVarmer.domain;
using DaaseVarmer.webserver.framework;


namespace DaaseVarmer.webserver.impl
{
    class HTMLFactory : IHTMLFactory
    {
        private Settings _settings;

        public HTMLFactory()
        {
            _settings = Settings.Instance;
        }

        public String GetHtmlResponse()
        {
            return getHeader() + getBody(getImgString() + getTemperatureTable(_settings.OutsiteTemp, "Outside Temperatures") + getTemperatureTable(_settings.SolarHeaterTemp, "Solar Heater Temperatures")) + getFooter();
        }

        public String getHtmlResponse(String request)
        {
            return getHeader() + getBody(request) + getFooter();
        }

        private String getHeader()
        {
            return "<html> <head>" + getJavaScript() + "<title>Canned Heater</title> </head>";
        }

        private String getJavaScript()
        {
            return "<script type='text/JavaScript'> function timedRefresh(timeoutPeriod) {	setTimeout('location.reload(true);',timeoutPeriod); } </script>";

        }

        private String getTemperatureTable(TemperatureReadings tr, String legend)
        {
            String result = "<div style=\"float:left;\"><table border='1'><caption>" + legend + "</caption>";
            for (int i = 0; i < 9; i++)
            {
                result += "<tr><td>" + tr.getPairAtIndex(i).getDate() + "</td><td>" + tr.getPairAtIndex(i).getTemperature() + "</td></tr>";
            }
            result += "</table></div>";
            return result;
            
        }

        private String getImgString()
        {
            return "<img src='https://api.pachube.com/v2/feeds/35670/datastreams/SolarHeaterTemp.png?width=730&height=250&colour=%23f15a24&duration=1week&title=Solar Heater Temperature&show_axis_labels=true&detailed_grid=true' alt='Solar Heater Temperature'/>";
        }

        private String getBody(String request)
        {
            return "<body onload=\"JavaScript:timedRefresh(10000);\">" + request + "</body>";
        }

        private String getFooter()
        {
            return "</html>";
        }

            }
}
